package com.wehealth.electrocardiograph_two_client.presenter

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ListView
import android.widget.PopupWindow
import com.wehealth.biz_ecg.ui.ECGMeasureActivity
import com.wehealth.electrocardiograph_two_client.R
import com.wehealth.electrocardiograph_two_client.activity.MainActivity
import com.wehealth.electrocardiograph_two_client.adapter.PatientUserAdapter
import com.wehealth.electrocardiograph_two_client.databinding.ActivityMainBinding
import com.wehealth.electrocardiograph_two_client.db.PatientUserDao
import com.wehealth.electrocardiograph_two_client.model.PatientUser
import com.wehealth.electrocardiograph_two_client.utils.AnimationEffect
import com.wehealth.electrocardiograph_two_client.utils.FileUtils
import com.wehealth.three.lib_common.utils.ToastUtil
import com.wehealth.three.lib_common.route.RouteFlag
import com.wehealth.three.lib_common.route.RouteHelper
import com.wehealth.three.lib_common.utils.SPUtil
import com.wehealth.three.lib_common.widget.PrivateDialog
import com.wehealth.three.lib_connect.constant.ConstantKey
import com.wehealth.three.lib_connect.constant.ConstantKey.ACCOUNT_PRIVATE_KEY
import com.wehealth.three.lib_connect.constant.ConstantKey.PATIENT_USER_AGE
import com.wehealth.three.lib_connect.constant.ConstantKey.PATIENT_USER_GENDER
import com.wehealth.three.lib_connect.constant.ConstantKey.PATIENT_USER_ID
import com.wehealth.three.lib_connect.constant.ConstantKey.PATIENT_USER_NAME
import com.wehealth.three.lib_connect.constant.ConstantKey.SETTING_IS_PACE_KEY
import com.wehealth.three.lib_connect.constant.ConstantKey.SETTING_SAVE_FILE_TYPE_KEY
import com.wehealth.three.lib_connect.constant.ConstantKey.SETTING_SEARCH_TYPE_KEY
import com.wehealth.three.lib_connect.constant.ConstantKey.USER_ECG_FILE_SAVE_TYPE
import com.wehealth.three.lib_connect.constant.ConstantKey.USER_ECG_SEARCH_TYPE
import com.wehealth.three.lib_connect.constant.ConstantKey.USER_WAVE_PACE
import java.util.Date

class MainPresenter(private val activity: MainActivity, val dataBinding: ActivityMainBinding) {
    companion object {
        const val HTML_TITLE_INFO = "隐私政策"
        const val HTML_URL_INFO = "file:///android_asset/cxd_private_agreement.html"
        const val HTML_TYPE_INFO = "text"
    }

    private var adapter: PatientUserAdapter? = null

    var gender = 0
    var age = 60


    fun showPrivateDialog() {
        val isAgree = SPUtil.getBoolean(ACCOUNT_PRIVATE_KEY, false)
        if (!isAgree) {
            PrivateDialog.getInstance().message("").sure(activity.resources.getString(R.string.btn_agree)).cancel(activity.resources.getString(R.string.btn_exit))
                .setOnTipItemClickListener(object : PrivateDialog.OnTipItemClickListener {
                    override fun cancelClick() {
                        SPUtil.putBoolean(ACCOUNT_PRIVATE_KEY, false)
                        activity.finishAffinity()
                    }

                    override fun sureClick() { //进入app，对话框结束。
                        SPUtil.putBoolean(ACCOUNT_PRIVATE_KEY, true)
                        Log.e("TAG", "PrivateDialog sure")
                    }

                    override fun userClick() {
                        navigateHtmlActivityPage(HTML_TITLE_INFO, HTML_URL_INFO, HTML_TYPE_INFO)
                    }

                    override fun termsClick() {
                    }
                }).create(activity)
        }

    }

    fun navigationSetPage() {
        RouteHelper.startActivity(activity, destination = RouteFlag.setting_page)
    }


    private fun navigateHtmlActivityPage(title: String, url: String, type: String) {
        val bundle = Bundle()
        bundle.putString("title", title)
        bundle.putString("url", url)
        bundle.putString("type", type)
        RouteHelper.startActivity(
            activity,
            destination = RouteFlag.html_page,
            bundle = bundle
        )
    }

    fun navigationEcgPage() {
        FileUtils.writeContentToFile(
            ConstantKey.adb_command_dir,
            ConstantKey.adb_command_usb.toCharArray()
        )
        if (!checkInputInfo()) return
        if (!SPUtil.getBoolean(ConstantKey.SETTING_IS_PLAY_VIDEO_KEY,false)) {
            val intent = Intent(activity,ECGMeasureActivity::class.java)
            intent.putExtra(PATIENT_USER_ID, dataBinding.mainId.text.trim().toString())
            intent.putExtra(PATIENT_USER_AGE, age)
            intent.putExtra(PATIENT_USER_GENDER, gender)
            intent.putExtra(PATIENT_USER_NAME, dataBinding.mainName.text.trim().toString())
            intent.putExtra(USER_ECG_SEARCH_TYPE, SPUtil.getInt(SETTING_SEARCH_TYPE_KEY, 0))
            intent.putExtra(USER_WAVE_PACE, SPUtil.getBoolean(SETTING_IS_PACE_KEY, false))
            intent.putExtra(USER_ECG_FILE_SAVE_TYPE, SPUtil.getInt(SETTING_SAVE_FILE_TYPE_KEY, 0))
            activity.startActivity(intent)
        } else {
            val intent = Intent(activity,ECGMeasureActivity::class.java)
            intent.putExtra(PATIENT_USER_ID, dataBinding.mainId.text.trim().toString())
            intent.putExtra(PATIENT_USER_AGE, age)
            intent.putExtra(PATIENT_USER_GENDER, gender)
            intent.putExtra(PATIENT_USER_NAME, dataBinding.mainName.text.trim().toString())
             intent.putExtra(USER_ECG_SEARCH_TYPE, SPUtil.getInt(SETTING_SEARCH_TYPE_KEY, 0))
            intent.putExtra(USER_WAVE_PACE, SPUtil.getBoolean(SETTING_IS_PACE_KEY, false))
            intent.putExtra(USER_ECG_FILE_SAVE_TYPE, SPUtil.getInt(SETTING_SAVE_FILE_TYPE_KEY, 0))
            intent.putExtra(ConstantKey.USER_ECG_CONNECT_TYPE, 2)
            activity.startActivity(intent)
        }

        val patUser = PatientUser()
        patUser.updateTime = Date().time
        patUser.idCardNo = dataBinding.mainId.text.trim().toString()
        patUser.age = age
        patUser.gender = gender
        patUser.name = dataBinding.mainName.text.trim().toString()
        PatientUserDao.getInstance().savePatientUser(patUser)
    }

    @SuppressLint("InflateParams")
    private fun initPopWin() {
        val popupView: View = activity.layoutInflater.inflate(R.layout.patient_user_pop, null)
        var popWin = PopupWindow(popupView, dataBinding.mainId.width, 260, true)
        popWin.isTouchable = true
        popWin.isOutsideTouchable = true
        popWin.setBackgroundDrawable(BitmapDrawable(activity.resources, null as Bitmap?))
        val listView = popupView.findViewById<ListView>(R.id.patientuser_lv)
        popupView.findViewById<View>(R.id.patientuser_title).visibility = View.GONE
        listView.adapter = adapter
        listView.onItemClickListener = AdapterView.OnItemClickListener { arg0, arg1, arg2, arg3 ->
            popWin.dismiss()
            val obj = arg0.getItemAtPosition(arg2) as Array<String>
            val pu: PatientUser = PatientUserDao.getInstance().getPatientUserByPatId(obj[0])
            if (pu != null) {
                dataBinding.mainId.setText("${pu.idCardNo}")
                dataBinding.mainAge.setText("${pu.age}")
                dataBinding.mainName.setText("${pu.name}")
                if (pu.gender === 0) {
                    dataBinding.mainGenderMale.isChecked = true
                } else {
                    dataBinding.mainGenderFemale.isChecked = true
                }
            }
        }
        popWin.showAsDropDown(dataBinding.mainId)
    }


    fun getCachePatient() {
        val pIds = PatientUserDao.getInstance().get10UserIDs()
        if (null == pIds || pIds.isEmpty()) {
            ToastUtil.toast("本地没有记录")
            return
        }
        adapter = PatientUserAdapter(activity, 1)
        adapter!!.addLists(pIds)
        initPopWin()
    }

    private fun checkInputInfo(): Boolean {
        if (TextUtils.isEmpty(dataBinding.mainId.text.toString().trim())) {
            AnimationEffect.setTransAni(dataBinding.mainId, -10, 10, 0, 0, 100)
            dataBinding.mainId.requestFocus()
            return false
        }

        if (TextUtils.isEmpty(dataBinding.mainAge.text.toString().trim())) {
            AnimationEffect.setTransAni(dataBinding.mainAge, -10, 10, 0, 0, 100)
            dataBinding.mainAge.requestFocus()
            return false
        }
        age = dataBinding.mainAge.text.toString().toInt()
        if (age > 140 || age <= 0) {
            ToastUtil.toast(activity.resources.getString(R.string.prompt_wrong_age))
            return false
        }

        if (dataBinding.mainGenderMale.isChecked) {
            gender = 0
        } else if (dataBinding.mainGenderFemale.isChecked) {
            gender = 1
        }

        if (TextUtils.isEmpty(dataBinding.mainName.text.toString().trim())) {
            AnimationEffect.setTransAni(dataBinding.mainName, -10, 10, 0, 0, 100)
            dataBinding.mainName.requestFocus()
            return false
        }
        return true
    }
}